package com.nopay.dxdwphone.ui.fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.dxdwphone.base.BaseFragment;
import com.nopay.dxdwphone.bean.response.GetCallTaskGroupResponse;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;

import java.util.ArrayList;
import java.util.List;

import com.nopay.dxdwphone.Constants;
import com.nopay.dxdwphone.R;
import com.nopay.dxdwphone.databinding.FragmentOutboundBinding;
import com.nopay.dxdwphone.ui.adapter.CallTaskGroupAdapter;
import com.nopay.dxdwphone.ui.ativity.MainActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 叫号任务分组
 */
public class OutboundFragment extends BaseFragment<FragmentOutboundBinding> {

    private final List<GetCallTaskGroupResponse.Data> dataList = new ArrayList<>();
    private CallTaskGroupAdapter adapter;

    @Override
    protected void loadData() {
        binding.rlRoot.setPadding(0, getStatusBarHeight(getActivity()), 0, 0);

        // 添加刷新头布局
        SinaRefreshView headerView = new SinaRefreshView(getActivity());
        headerView.setArrowResource(R.mipmap.arrow);
        headerView.setTextColor(0xff745D5C);
        binding.refresh.setHeaderView(headerView);
        // 禁止上拉加载更多
        binding.refresh.setEnableLoadmore(false);

        binding.rvHistory.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new CallTaskGroupAdapter(dataList);
        adapter.setOnItemChildClickListener((baseAdapter, view, position) -> {
            // TODO 跳转到任务对应的列表界面
            if(!onCheckPermissionsAndRequest()) return;

            ((MainActivity) getActivity()).gotoCallTask(adapter.getItem(position));
        });

        binding.rvHistory.setAdapter(adapter);
        binding.refresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                requestCallTaskData(() -> {
                    refreshLayout.finishRefreshing();
                    adapter.notifyDataSetChanged();
                });
            }
        });

        // 文件导入
        binding.btnImport.setOnClickListener(v -> requestStoragePermission());
        // 手动拨号
        binding.btnTel.setOnClickListener(v -> onCheckPermissions());

        binding.refresh.startRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(getUserVisibleHint()) {
            binding.refresh.startRefresh();
        }
    }

    public void hasTaskClear() {
        if(binding != null) binding.refresh.startRefresh();
    }

    private static final String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_CONTACTS, Manifest.permission.READ_CALL_LOG,
            Manifest.permission.WRITE_CONTACTS, Manifest.permission.WRITE_CALL_LOG,
            Manifest.permission.RECORD_AUDIO, Manifest.permission.CALL_PHONE};

    private void onCheckPermissions() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionList = new ArrayList<>();

            for (String permission : PERMISSIONS) {
                if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                    permissionList.add(permission);
                }
            }

            if(permissionList.size() > 0) {
                String[] permissions = new String[permissionList.size()];
                for (int i = 0; i < permissionList.size(); i++) {
                    permissions[i] = permissionList.get(i);
                }

                ActivityCompat.requestPermissions(getActivity(), permissions, 100);
                return;
            }
        }

        ((MainActivity) getActivity()).gotoTel();
    }

    private boolean onCheckPermissionsAndRequest() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionList = new ArrayList<>();

            for (String permission : PERMISSIONS) {
                if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                    permissionList.add(permission);
                }
            }
            if(permissionList.size() > 0) {
                String[] permissions = new String[permissionList.size()];
                for (int i = 0; i < permissionList.size(); i++) {
                    permissions[i] = permissionList.get(i);
                }
                ActivityCompat.requestPermissions(getActivity(), permissions, 120);
                return false;
            }
        }
        return true;
    }

    private void requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
        } else {
            ((MainActivity) getActivity()).gotoFileImport();
        }
    }

    private void requestCallTaskData(OnRequestDataCompleteCallback callback) {
        String phone = SPUtils.getInstance().getString(Constants.SP_PHONE, "");
        api.doGetCallTaskGroup(phone).enqueue(new Callback<GetCallTaskGroupResponse>() {
            @Override
            public void onResponse(Call<GetCallTaskGroupResponse> call, Response<GetCallTaskGroupResponse> response) {
                dataList.clear();
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        List<GetCallTaskGroupResponse.Data> callTaskGroup = response.body().getData();
                        if(callTaskGroup != null && callTaskGroup.size() > 0) {
                            dataList.addAll(callTaskGroup);
                        }
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }

                if(callback != null) callback.onComplete();
            }

            @Override
            public void onFailure(Call<GetCallTaskGroupResponse> call, Throwable t) {
                if(callback != null) callback.onComplete();
                if(getActivity() != null) ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
            }
        });
    }

    public interface OnRequestDataCompleteCallback {

        void onComplete();
    }
}
